<template>
  <div class="p-2 container">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="120px">
            <el-form-item label="布防任务名称" prop="defenseTaskName">
              <el-input v-model="queryParams.defenseTaskName" placeholder="请输入布防任务名称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="更新时间" prop="updateTime">
              <el-date-picker v-model="queryParams.updateTime" type="date" placeholder="请选择" />
            </el-form-item>
            <!-- <el-form-item label="执行角色id" prop="executeRoleId">
              <el-input v-model="queryParams.executeRoleId" placeholder="请输入执行角色id" clearable @keyup.enter="handleQuery" />
            </el-form-item> -->
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never" style="flex: 1; display: flex; flex-direction: column; position: relative">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button v-hasPermi="['camera:camera-defense-task:add']" type="primary" plain icon="Plus" @click="handleAdd">新增 </el-button>
          </el-col>
          <!-- <el-col :span="1.5">
            <el-button v-hasPermi="['camera:camera-defense-task:edit']" type="success" plain icon="Edit" :disabled="single" @click="handleUpdate()">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['camera:camera-defense-task:remove']" type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button v-hasPermi="['camera:camera-defense-task:export']" type="warning" plain icon="Download" @click="handleExport">导出</el-button>
          </el-col> -->
          <right-toolbar v-model:showSearch="showSearch" @query-table="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table v-loading="loading" :data="cameraDefenseTaskList" height="calc(100% - 30px)" @selection-change="handleSelectionChange">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="布防任务名称" align="center" prop="defenseTaskName" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.taskType === 2">-</span>
            <span v-else>{{scope.row.defenseTaskName}}</span>
          </template>
        </el-table-column>
        <el-table-column label="布防类型" align="center" prop="taskType" show-overflow-tooltip>
          <template #default="scope">
            <span v-if="scope.row.taskType === 1">AI布防</span>
            <span v-else-if="scope.row.taskType === 2">人脸布防</span>
            <span v-else>- -</span>
          </template>
        </el-table-column>
        <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip />
        <el-table-column label="操作" align="center" fixed="right" :min-width="100" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button
                v-hasPermi="['camera:camera-defense-task:edit']"
                link
                type="primary"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button
                v-hasPermi="['camera:camera-defense-task:remove']"
                link
                type="primary"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" :total="total" @pagination="getList" />
    </el-card>
    <!-- 添加或修改布防任务对话框 -->
    <el-drawer v-model="dialog.shouAdd" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="cameraDefenseTaskFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="form.taskType" clearable placeholder="请选择">
            <el-option :key="1" label="AI布防" :value="1" />
            <el-option :key="2" label="人脸布防" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.taskType == 1" label="任务名称" prop="defenseTaskName">
          <el-input v-model="form.defenseTaskName" placeholder="请输入布防任务名称" />
        </el-form-item>
        <el-form-item v-if="form.taskType == 1" label="布防时段" prop="startEndTime">
          <el-time-picker
v-model="startEndTime"
          format="HH:mm:ss"
value-format="HH:mm:ss"
          is-range
range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          @change="handeleTimePicker"
          />
        </el-form-item>
        <el-form-item v-if="form.taskType == 1" label="AI算法" prop="aiAlgorithm">
          <el-select v-model="form.aiAlgorithm" clearable placeholder="请选择">
            <el-option v-for="dict in ai_algorithm_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="绑定设备" prop="bindEquipmentId">
          <el-select v-model="form.bindEquipmentId" filterable clearable placeholder="请选择设备">
            <el-option v-for="item in equipmentList" :key="item.equipmentId" :label="item.equipmentName" :value="item.equipmentId" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.taskType == 2" label="人员类型" prop="userType">
          <el-select v-model="form.userType" clearable placeholder="请选择">
            <el-option :key="1" label="黑名单人员" :value="1" />
            <el-option :key="2" label="其他人员" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="form.taskType == 2 && form.userType == 2" label="上传照片" prop="fileIds">
          <!-- <el-upload
            class="avatar-uploader"
            :action="upload.url"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            name="file"
            :headers="upload.headers"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload> -->
          <ImageUpload v-model="form.fileIds" :file-size="2"/>
        </el-form-item>
        <el-form-item label="告警类型" prop="alarmType">
          <el-select v-model="form.alarmType" clearable placeholder="请选择">
            <el-option v-for="dict in alarm_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="告警事件" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入告警事件" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup name="cameraDefenseTask" lang="ts">
import {
  addcameraDefenseTask,
  delcameraDefenseTask,
  getcameraDefenseTask,
  listcameraDefenseTask,
  updatecameraDefenseTask
} from '@/api/security/video-perimeter/camera-defense-task';
import { cameraDefenseTaskForm, cameraDefenseTaskQuery, cameraDefenseTaskVO } from '@/api/security/video-perimeter/camera-defense-task/types';
import { listEquipmentInfo } from '@/api/facility/equipment-info';
import { globalHeaders } from '@/utils/request';

import type { UploadProps } from 'element-plus';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';
import { parseTime } from '@/utils/linx';

const imageUrl = ref('');

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  form.value.fileIds = imageUrl.value;
};

const upload = reactive<UploadOption>({
  headers: globalHeaders(),
  url: import.meta.env.VITE_APP_BASE_API + '/resource/oss/upload'
});

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!');
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!');
    return false;
  }
  return true;
};

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { ai_algorithm_type, alarm_type } = toRefs<any>(proxy?.useDict('ai_algorithm_type', 'alarm_type'));

const cameraDefenseTaskList = ref<cameraDefenseTaskVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const equipmentList = ref<any[EquipmentInfoVO]>([]);

const queryFormRef = ref<ElFormInstance>();
const cameraDefenseTaskFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: cameraDefenseTaskForm = {
  cameraDefenseTaskId: undefined,
  remark: undefined,
  defenseTaskName: undefined,
  executeRoleId: undefined,
  startEndTime: undefined
};
const data = reactive<PageData<cameraDefenseTaskForm, cameraDefenseTaskQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    defenseTaskName: undefined,
    executeRoleId: undefined,
    params: {}
  },
  rules: {
    cameraDefenseTaskId: [{ required: true, message: '主键不能为空', trigger: 'blur' }],
    defenseTaskName: [{ required: true, message: '布防任务名称不能为空', trigger: 'blur' }, { max: 20, message: '布防任务名称不能超过20个字符', trigger: 'blur' }],
    executeRoleId: [{ required: true, message: '执行角色id不能为空', trigger: 'blur' }],
    taskType: [{ required: true, message: '任务类型不能为空', trigger: 'blur' }],
    bindEquipmentId: [{ required: true, message: '绑定设备不能为空', trigger: 'blur' }],
    userType: [{ required: true, message: '人员类型不能为空', trigger: 'blur' }],
    alarmType: [{ required: true, message: '告警类型不能为空', trigger: 'blur' }],
    fileIds: [{ required: true, message: '上传照片不能为空', trigger: 'change' }],
    time: [{ required: true, message: '布防时段不能为空', trigger: 'blur' }],
    aiAlgorithm: [{ required: true, message: 'AI算法不能为空', trigger: 'blur' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

// 布防时段change事件

/** 任务时段选择处理 */
let startEndTime = ref([])
const handeleTimePicker = async () => {
  form.value.startTime = startEndTime.value[0];
  form.value.endTime = startEndTime.value[1];
};

/** 查询布防任务列表 */
const getList = async () => {
  loading.value = true;
  const res = await listcameraDefenseTask(queryParams.value);
  cameraDefenseTaskList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.shouAdd = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  cameraDefenseTaskFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: cameraDefenseTaskVO[]) => {
  ids.value = selection.map((item) => item.cameraDefenseTaskId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getEquipmentList();
  dialog.shouAdd = true;
  dialog.title = '添加布防任务';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: cameraDefenseTaskVO) => {
  reset();
  const _cameraDefenseTaskId = row?.cameraDefenseTaskId || ids.value[0];
  const res = await getcameraDefenseTask(_cameraDefenseTaskId);
  Object.assign(form.value, res.data);
  if (res.data.startTime && res.data.endTime) {
    startEndTime.value = [res.data.startTime, res.data.endTime];
  }
  form.value.alarmType = String(res.data.alarmType);
  form.value.aiAlgorithm = String(res.data.aiAlgorithm);
  getEquipmentList();
  console.log('form.value', form.value);
  dialog.shouAdd = true;
  dialog.title = '修改布防任务';
};

/** 获取设备列表 */
const getEquipmentList = async () => {
  loading.value = true;
  const res = await listEquipmentInfo();
  if (res.code === 200) {
    equipmentList.value = res.rows;
    loading.value = false;
  }
};

/** 提交按钮 */
const submitForm = () => {
  if (form.value.startEndTime && form.value.startEndTime.length > 0) {
    form.value.startTime = parseTime(form.value.startEndTime[0], '{h}:{i}:{s}')
    form.value.endTime = parseTime(form.value.startEndTime[1], '{h}:{i}:{s}');
  }
  cameraDefenseTaskFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.cameraDefenseTaskId) {
        await updatecameraDefenseTask(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addcameraDefenseTask(form.value).finally(() => (buttonLoading.value = false)); // 新增
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.shouAdd = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: cameraDefenseTaskVO) => {
  const _cameraDefenseTaskIds = row?.cameraDefenseTaskId || ids.value;
  await proxy?.$modal.confirm('是否确认删除布防任务编号为"' + _cameraDefenseTaskIds + '"的数据项？').finally(() => (loading.value = false));
  await delcameraDefenseTask(_cameraDefenseTaskIds);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'camera/camera-defense-task/export',
    {
      ...queryParams.value
    },
    `camera-defense-task_${new Date().getTime()}.xlsx`
  );
};

onMounted(() => {
  getList();
});
</script>
<style lang="scss" scoped>
:deep(.el-card__header) {
  height: 60px;
}

:deep(.el-card__body) {
  height: calc(100% - 60px);
}

:deep(.pagination-container) {
  margin-top: 0;
}

.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
